package util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.Toast;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import data.SharedPreferencesUtils;

/**
 * Created by Administrator on 2016/7/11.
 *对字符串的操作
 */
public class StringUtil {

    private static StringUtil mStringUtil;
    private Map<String,Object> map;
    private static List<String> mListPust = new ArrayList<>();
    private Logger mLogger = Logger.getLogger(StringUtil.class);
    public static synchronized StringUtil getStringUtilNew(){
        if(mStringUtil == null){
            mStringUtil = new StringUtil();
        }
        return mStringUtil;
    }

    /**
     * 验证是否是手机号码
     */
    public boolean isMobile(String mobiles) {

        if(mobiles.length() == 11){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 验证密码
     */
    public boolean getStatePassword(String password) {
        String state = "[0-9a-zA-Z]{5,12}$";
        if (TextUtils.isEmpty(password)) return false;
        else return password.matches(state);
    }

    /**
     * 验证密码
     */
    public boolean getStateHttp(String string) {
        String state = "(http|ftp|https):\\/\\/([\\w.]+\\/?)\\S*";
       return string.matches(state);
    }

    /**
     * 得到一个JSON字符
     * @param map HashMap 集合
     * @return JSON字符
     */
    public String hashMapToJson(HashMap map) {
        if (map.isEmpty()) return "{}";
        try {
            StringBuilder stringBuilder = new StringBuilder("{");
            for (Object o : map.entrySet()) {
                Map.Entry e = (Map.Entry) o;
                stringBuilder.append("\"").append(e.getKey()).append("\":");
                stringBuilder.append("\"").append(e.getValue()).append("\",");
            }
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
            stringBuilder.append("}");
            return stringBuilder.toString();
        }catch (Exception e){
            return "{}";
        }
    }

    /**
     * 年月日 时分秒
     */
    public String getTimeInstance(){
        Date da = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(da);
    }

    /**
     * 比较 timeString 和现在的大小
     * @param timeString 传入的时间
     *                   time 分钟
     * @return true 转入的时间大于现在的时间
     */
    public long compareTime(String timeString,int time){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date1 = sdf.parse(timeString);
            Date date2 = new Date();
            LogUtil.eE("","(date1.getTime() + time*60000)"+(((date1.getTime() + time*60000) - date2.getTime())/60000)+"");
            if((date1.getTime() + time*60000) > date2.getTime()){
                return (((date1.getTime() + time*60000) - date2.getTime())/60000);
            }else {
                return -1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 返回当前时间戳
     */
    public long getTimeCurrent(){
          Date date = new Date();
          long str = date.getTime();
          LogUtil.eE("JSONString",str+"");
          return str;
      }

    /**
     * @return 参数签名
     */
    public String getSign(String keyword,String json,String token,String userid,long time){
           String stringjson="keyword="+keyword+"&params="+json+"&time="+time+"&token="+token+"&userid="+userid+"&key=niulang2016";
           LogUtil.eE("JSONString",stringjson);
           return getMD5String(stringjson);
    }

    /**
     * 拉去推送消失 签名操作
     * @param map 参数包
     */
    public String getPushSign(Map<String,String> map ){
        //排序容器
        List<Map.Entry<String, String>> infoIds =
                new ArrayList<Map.Entry<String, String>>(map.entrySet());

        //排序
        Collections.sort(infoIds, new Comparator<Map.Entry<String,String>>()  {
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                //return (o2.getValue() - o1.getValue()); //根据值排序
                return (o1.getKey()).toString().compareTo(o2.getKey());//根据键排序
            }
        });
        String param ="";
        //排序后
        for (int i = 0; i < infoIds.size(); i++) {
            String id = infoIds.get(i).toString();
            if(i!=infoIds.size()-1){
                param=param+id+"&";
            }else{
                param=param+id;
            }
        }

        System.out.println(param);
        //签名
        String serSign = getMD5String(param);

        return serSign;
    }

    /**
     * @param params 参数包
     * @param token token
     * @param userid userid
     * @param keyword 接口关键字
     * @param sign 签名
     * @return 返回Map集合对象 用于网络请求
     */
    public Map<String,Object> getMapNew(Context context,String params,String token,String userid,String keyword,String sign,long time){
          if(map == null){
              map = new HashMap<>();
          }
          map.put("params",params);
          map.put("token",token);
          map.put("userid",userid);
          map.put("time",time);
          map.put("keyword",keyword);
          map.put("sign",sign);
          map.put("apMac",getInformation.getNewGetInformation(context).getWiFiMac());
          map.put("apName",getInformation.getNewGetInformation(context).getWIFIName());
          map.put("NF_callid",StringUtil.getStringUtilNew().getRandom());
          map.put("appType",1);
          map.put("version",getInformation.getNewGetInformation(context).getVersion());
        return map;
    }

    /**
     * MD5加密
     */
    public String getMD5String(String s) {

        if(s == null || s.equals("")){
            return null;
        }

        char hexDigits[] = {'0', '1', '2', '3', '4',
                '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] btInput = s.getBytes("UTF-8");
            //获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            //使用指定的字节更新摘要
            mdInst.update(btInput);
            //获得密文
            byte[] md = mdInst.digest();
            //把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 判断mac的情况
     */
     public boolean judgeMac(String mac){
          if(mac.equals("") || mac.equals("02:00:00:00:00:00") || mac.equals("00:00:00:00:00:00")){
              return false;
          }else {
              return true;
          }
    }

    /**
     * 判断联网的参数
     */
     boolean judgeNetWorkstateParameter(Context context,String ip,String ip1){

         if(ip == null || ip1 == null){
             Toast.makeText(context,"ip没有获取到",Toast.LENGTH_SHORT).show();
             return false;
         }else {
             if(ip.equals("")){
                 if(ip1.equals("")){
                     Toast.makeText(context,"ip没有获取到",Toast.LENGTH_SHORT).show();
                     return false;
                 }
             }
         }

        if(getInformation.getNewGetInformation(context).getIMAC().equals("")){
            Toast.makeText(context,"设备mac没有获取到",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(getInformation.getNewGetInformation(context).getWiFiMac().equals("")){
            Toast.makeText(context,"apMac没有获取到",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 提取异常,并判断，并提示
     */
    public void getExceptionCode(Context context,String error){

        LogUtil.eE("error",error.toString());
        int sign = error.indexOf(":");
        if(sign <0){
            exception(context,error.toString());
        }else {
            String string = error.substring(0,sign).trim();
            exception(context,string);
        }
    }

    /**
     * 获取模式集合
     */
    ArrayList getPatternList(JSONArray jsonArray) throws JSONException {
        ArrayList list = new ArrayList();
        for (int i = 0; i <jsonArray.length() ; i++) {
            list.add(jsonArray.getInt(i));
        }
        return list;
    }

    /**
     *判断联网方式
     * 2  直接提示购买套餐
     * 1  直接提示购买押金
     * 3  选择上网时长
     * 4  打开上网选择的页面
     * 0 没有资源
     */
    public int getjudeNetWorksteMode(int banding,int erweima,int firstfree,int combonum,int vip,int vipnum){
           if(vipnum == 0){
               if(combonum !=0 && banding == 0 && erweima == 0 && firstfree == 0 && vip==0){
                   return 2;
               }else if(combonum == 0 && banding == 0 && erweima == 0 && firstfree == 0 && vip !=0){
                   return 1;
               }else if(combonum == 0 && banding == 0 && erweima == 0 && firstfree == 0 && vip == 0){
                   return 0;
               }else {
                   return 4;
               }
           }else {
               return 3;
           }
    }

    /**
     *返回UI类型或 当前的模式
     * 0 代表是  没有模式
     * 1 代表是  会员
     * 2 代表是  套餐
     * 3 代表是  免费
     * 4 代表是  绑定
     */
    public int judgeUIType(int pattern){
        if( pattern> 0 && pattern<10 ){
            return 4;
        }else if(pattern >=10 && pattern< 20){
            return 2;
        }else if(pattern >=20 && pattern< 30){
            return 1;
        }else if(pattern >=30 && pattern< 40){
            return 3;
        }else {
            return 0;
        }
    }

    /**
     *判断押金/套餐是否同时存在
     */
    public boolean getDepositPackageState(Context context){
        ArrayList list = (ArrayList) SharedPreferencesUtils.getParam(context,HomeUtil.mAppPatternArray,"list");
        int count = 0;
        for (int i = 0; i < list.size() ; i++) {
                 int pattern = (int) list.get(i);
                 if(judgeUIType(pattern) == 1 || judgeUIType(pattern) == 2){
                     count++;
                 }
        }
        if(count == 2){
            return true;
        }
        return false;
    }

    /**
     * 找在集合中的押金
     */
    public int getLookForDeposit(Context context){
        ArrayList list = (ArrayList) SharedPreferencesUtils.getParam(context,HomeUtil.mAppPatternArray,"list");
        for (int i = 0; i <list.size(); i++) {
            int pattern = (int) list.get(i);
            if(judgeUIType(pattern) == 1){
                return pattern;
            }
        }
        return 0;
    }

    /**
     * 找在集合中的套餐
     */
    public int getLookForPackage(Context context){
        ArrayList list = (ArrayList) SharedPreferencesUtils.getParam(context,HomeUtil.mAppPatternArray,"list");
        for (int i = 0; i <list.size(); i++) {
            int pattern = (int) list.get(i);
            if(judgeUIType(pattern) == 2){
                return pattern;
            }
        }
        return 0;
    }

    /**
     * 模式在10 到 20 之间 模式套餐
     */
    public boolean getMonthlyState(int pattern){
            if(pattern >=10 && pattern< 20){
                return true;
            }
        return false;
    }

    /**
     *修改服务器 (图片)
     */
    public String getFeq(String fwq,String string){
        String s = getReverse(fwq);
        int i = s.indexOf("/");
        String ss = s.substring(i,s.length());
        return getReverse(ss)+string;
    }

    /**
     *修改服务器 (上传头像)
     */
    public String uploadHead(String fwq){
        String s = getReverse(fwq);
        int i = s.indexOf("/");
        if(i>0){
            String ss = s.substring(i+1,s.length());
            int i1 = ss.indexOf("/");
            if(i1>0){
                String ss1 = ss.substring(i1+1,ss.length());
                return getReverse(ss1);
            }
        }
        return "";
    }

    /**
     *字符串反转
     */
    private String getReverse(String string){
        StringBuffer stringBuffer = new StringBuffer(string);
        return stringBuffer.reverse().toString();
    }

    /**
     * 判断有没有安装对应包名的app
    * check the app is installed
    */
    public boolean isAppInstall(Context context,String packagename)
    {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        }catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }
        return packageInfo != null;
    }

    /**
     * ping网络  这个操作应该在子线程中执行 如果在主线程会影响UI
     * @param str
     * @return
     */
    public int getPing(String str) {
        int resault = 2;
        Process p;
        try {
            //ping -c 3 -w 100  中  ，-c 是指ping的次数 3是指ping 3次 ，-w 100  以秒为单位指定超时间隔，是指超时时间为100秒
            p = Runtime.getRuntime().exec("ping -c 1 " + str);
            int status = p.waitFor();
           /* InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null){
                buffer.append(line);
            }*/
            if (status == 0) {
                resault = status;
            } else {
                resault = status;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return resault;
    }

    /**
     * writeObject 方法负责写入特定类的对象的状态，以便相应的 readObject 方法可以还原它
     * 最后，用Base64.encode将字节文件转换成Base64编码保存在String中
     * @param object 待加密的转换为String的对象
     * @return String   加密后的String
     */
    public String objectString(Object object) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(object);
            String string = new String(Base64.encode(byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
            objectOutputStream.close();
            return string;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 使用Base64解密String，返回Object对象
     *
     * @param objectString 待解密的String
     * @return object      解密后的object
     */
    public Object stringObject(String objectString) {
        byte[] mobileBytes = Base64.decode(objectString.getBytes(), Base64.DEFAULT);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(mobileBytes);
        ObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Object object = objectInputStream.readObject();
            objectInputStream.close();
            return object;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 判断服务器地址 是否能联网
     * @param url
     * @return
     */
    public boolean getFwqWhetherNetworking(String url){
        String fwq = url.substring(url.indexOf("//")+2,url.indexOf(":8080"));
        LogUtil.eE("",fwq);
        int judge = getPing(fwq);
        return judge == 0;
    }

    /**
     * 生成一个20位的随机数
     *
     */
    public String getRandom(){
        String strRand="" ;
        for(int i=0;i<10;i++){
            strRand += String.valueOf((int)(Math.random() * 10)) ;
        }
      return strRand;
    }

    /**
     * 判断错误码
     */
    private void exception(Context context,String string){
        if(string.length()>=20){
            String string3 = string.substring(string.length()-20,string.length());
            mLogger.info("网络请求不通的提示---exception--->string3--"+string3);
            if(string3.contains("cketTimeoutException")){
                Toast.makeText(context,"响应超时,请检查网络",Toast.LENGTH_SHORT).show();
            }else if(string3.contains("nectTimeoutException")){
                Toast.makeText(context,"请求超时,请检查网络",Toast.LENGTH_SHORT).show();
            }else if(string3.contains("UnknownHostException")){
                Toast.makeText(context,"无法连接服务器,请检查网络",Toast.LENGTH_SHORT).show();
            }else if(string3.contains("HostConnectException")){
                Toast.makeText(context,"无法连接服务器,请检查网络",Toast.LENGTH_SHORT).show();
            }else if(string3.contains("JsonSyntaxException")){
                Toast.makeText(context,"服务器超时或者异常,请稍等",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(context,"网络异常,请检查",Toast.LENGTH_SHORT).show();
            }

        } else if(string.contains("Not Found")){Toast.makeText(context,"服务器异常,请稍等",Toast.LENGTH_SHORT).show();
        } else { Toast.makeText(context,"网络异常,请检查",Toast.LENGTH_SHORT).show();}
    }

    /**
     * 添加推送数据 type 0 极光 1 本地
     */
    public void setPhshContext(Context context,String string,int type,List<String> list){
        if(type == 0){
            mListPust.add(string);
            SharedPreferencesUtils.setParam(context, "Pull_list", mListPust);
        }else if(type == 1){
            mListPust = list;
        }
    }

    /**
     * 清理推送的数据
     * 0 全部  1代表最后
     */
    public void clearPhshData(Context context,int i){
        if(mListPust !=null){
            if(i == 0){
                mListPust.clear();
            }else if(i == 1){
                if(mListPust.size() > 0){
                    mListPust.remove(mListPust.size()-1);
                }
            }
        }

        SharedPreferencesUtils.setParam(context, "Pull_list", mListPust);
    }

    /**
     * 数组转换成List
     */
    List arrayList(JSONArray jsonArray) throws JSONException {
         List<String> list = new ArrayList<>();
        for (int i = 0; i <jsonArray.length() ; i++) {
             JSONObject jsonObject = jsonArray.getJSONObject(i);
             list.add(jsonObject.toString());
        }
        return list;
    }

    /**
     *获取集合的最后一个
     */
    public String getPullLast(){
        if(mListPust.size() > 0 ){
            return mListPust.get(mListPust.size()-1);
        }else {
            return "";
        }
    }

    /**
     * 返回推送消息
     */
    public JSONArray getPhshContext(){
        //JSONObject jsonObject =  JSONObject();
        JSONArray jsonArray = new JSONArray(mListPust);
        LogUtil.eE("","...jsonArray.toString()...."+jsonArray);
        return jsonArray;
    }
}
